package serverManager;

import java.io.File;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;

import os_listener.ServerUpdates;
import db_manager.Manager;

/**
 * this class is the class that response to the user attempt to make connection (it suspends it)
 */
public class ConnectionWithSpy extends HttpServlet
{
	/**
	 * this function handle the case that the user is trying to make contact with the server
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
	{
		// the case that the user was trying to connect to the server through the client project
		if (request.getRequestURI().contains("/serverManager.ConnectionWithSpy")) 
		{
			String user_name = request.getParameter("user_name");
			// creating a new continuation for this user
			Continuation cc = ContinuationSupport.getContinuation(request, null);
			response.setContentType("text/html"); 
			ConnectionsKeeper ck = ConnectionsKeeper.getInstance();
			Manager manager = Manager.getInstance();
			File sessionFile = new File("C:\\Program Files\\m&l_dropbox_server\\hibernate.cfg.xml");
			SessionFactory sessionFactory = new Configuration().configure(sessionFile).buildSessionFactory();
			Session session = sessionFactory.openSession();
			// getting the user id
			long userId = manager.checkUserId(session, user_name);
			session.flush();
			// adding the continuation to the continuation keeper class
			boolean ok = ck.addConnection(cc, userId);
			// the case that entering the cc succeeded
			if(ok)
			{
				// going into suspend
				try
				{
					//suspending the connection until resume
					cc.suspend(0); 

					//resumed
					ServerUpdates su = ConnectionsKeeper.getInstance().getNewest_su();
					UpdatesManager um = new UpdatesManager(su);
					// Handling update
					um.start();

				}
				catch (Exception e){}
			}
		}
    }
}
